<?php


namespace App\Http\Admin\Controllers;

use Illuminate\Http\Request;
use App\Http\Admin\Controllers\Controller as Controller;
use App\Http\OS\Controllers\IndexController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use function PHPSTORM_META\type;
use Illuminate\Support\Facades\Redis;
use App\Http\Authentication\UserAuthentication;



/*
 *  案件表接口
 *  @author 小林《1814992057@qq.com》
 *  @datetime   2019/8/23
*/

class CaseController extends Controller
{
//    use UserAuthentication;

    public function add_case(Request $request)
    {

        $token = getToken($request);
        $uid =Redis::get("code:".$token);

    
        $imgs=$request->all()['imgs'];

        $title=$request->all()['title'];
        $imgurl=[];
        $imgsNew=[];

        $content="";
        $courtid=0;//法院id
        $case_number=0;//案号
        $case_number_time=0;//案号时间
        $json_content=array();
        $json_contents=array();
        $case_title="";
        $status=0;
        $json=array();
        $num =0;
        $y=[];
        $b=[];
        $lv=[];

        foreach ($imgs as $k=>$v){
            // var_dump(intval(explode(".",$v->getClientOriginalName())[0])-1);
            $imgsNew[intval(explode(".",$v->getClientOriginalName())[0])-1]=$v;
        }
        
        // var_dump($imgsNew);
        // die;
        foreach ($imgsNew as $k=>$v){


            $imgName="case/".date("Y",time())."/".date("m",time())."/".date("d",time())."/".date("YmdHis",time())."/".rand(1000,9999).rand(1000,9999).".".$v->getClientOriginalExtension();

            $imgurl[$k] = Oss($v,$imgName)['info']['url'];

            try{
                $json[$k]=json_decode(returnImgJson2($imgurl[$k]),1);
            }catch (Exception $e){
                return [
                    'status_code'      => 200,
                    'message'     =>  '操作成功',
                    'data' => $title."失败"
                ];
            }



            if(count($imgsNew)-1==$k){

                foreach ($json[$k][''] as $kk=>$vv){
                    if($vv['word']=="审"||$vv['word']=="代理审"){
                        foreach ($json[$k]['prism_wordsInfo'] as $kkk=>$vvv){
                            if($kkk>=$kk){
                                unset($json[$k]['prism_wordsInfo'][$kkk]);
                            }
                        }
                        break;
                    }
                }

            }


            $json_content=$json[$k]['prism_wordsInfo'];
            $key=0;
            $bigX=500;

           
            foreach ($json_content as $kk=>$vv){
                if($vv['pos'][0]['x'] < $bigX) $bigX=$vv['pos'][0]['x'];
            }
            $json_contents[]=$json_content;
            if($num==0){

                foreach ($json_content as $kk=>$vv){

                    switch ($kk){
                        case 0:
                            $courtDB=DB::table('C_court')->where('name','like',"%".$vv['word']."%")->first();
                            if($courtDB) $courtid=$courtDB['id'];

                           break;
                        case 1:
                            $status=4;
                            $case_status=substr($vv['word'],-9,9);
                            if(array_key_exists($case_status,create(['case_status'])['case_status'])) $status=create(['case_status'])['case_status'][$case_status];
                            break;
                        case 2:
                            $case_number=$vv['word'];
                            $case_number_time=substr($vv['word'],1,4);
                            break;
                        default:
                            if($vv['pos'][0]['y']-$json_content[$kk-1]['pos'][0]['y']<=3){
                                $content.=$vv['word'];
                            }else {
                                if ($vv['pos'][0]['x'] - $bigX < 50) {
                                    $content .= $vv['word'];
                                } else {
                                    $content = $content . "\n" . $vv['word'];
                                }
                            }


                        break;
                    }
                }
            }else{
                foreach ($json_content as $kk=>$vv){


                        if($vv['pos'][0]['x']-$bigX < 50){
                            $content.=$vv['word'];
                        }else{
                            $content=$content."\n".$vv['word'];
                        }

                }
            }


            $num++;

        }

        $datas = explode("\n" ,$content);

        foreach ($datas as $kk=>$vv){
            if(preg_match('/^(原告：)/u',$vv)){
                $y[]=explode("，",$vv);
                $w=1;
            }
            if(preg_match('/^(被告：)/u',$vv)){
                $b[]=explode("，",$vv);
                $w=2;
            }
            if(preg_match('/^(委托诉讼代理人：)(.*)(律师。)$/u',$vv)){
                $lv[]=explode("，",$vv);
            }
        }


        $res = DB::table('C_case')->insertGetId(
            [
                'title'=>$title,
                'court'=>$courtid,
                'case_number'=>$case_number,
                'case_number_time'=>$case_number_time,
                'create_time'=>date("Y-m-d H:i:s",time()),
                'uid'=>$uid,
                'status'=>$status
            ]
        );

        $res2 = DB::table('C_case_data')->insertGetId(
            [
                'content'=>$content,
                'json_content'=>json_encode($json_contents),
                'imgs'=>json_encode($imgurl),
                'cid'=>$res
            ]
        );

//        $res3=DB::table("C_case_cp")->


        if(count($y)>0){
            foreach ($y as $k=>$v){
                $name = str_replace("原告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                $age = str_replace("出生","",$v[2]);
                $age = str_replace(" ","",$age);
                $age =date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>1,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($b)>0){
            foreach ($b as $k=>$v){
                $name = str_replace("被告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                $age = str_replace("出生","",$v[2]);
                $age = str_replace(" ","",$age);
                $age = date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>2,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($lv)>0){
            foreach ($lv as $k=>$v){

                $lawyerName=str_replace("委托诉讼代理人：","",$v[0]);
                $lawyerName = str_replace(" ","",$lawyerName);
                $lawyerOfficeName=str_replace("律师","",$v[1]);
                $lawyerOfficeName = str_replace(" ","",$lawyerOfficeName);
                $lawyerOfficeName = str_replace("。","",$lawyerOfficeName);
                
                $lawyerOffice=DB::table('C_lawyerOffice')->where('name','like','%'.$lawyerOfficeName.'%')->first();



                if(!$lawyerOffice){
                    $lawyerOffice=DB::table('C_lawyerOffice')->insertGetId([
                        'name'=>$lawyerOfficeName,
                        'status'=>1
                    ]);
                }else{
                    $lawyerOffice=$lawyerOffice['id'];
                }


                $lawyer=DB::table('C_lawyer')->where(
                    [
                        ['name','like','%'.$lawyerName.'%'],
                        ['loid','=',$lawyerOffice]
                    ]
                )->first();



                if(!$lawyer){
                    $lawyer=DB::table('C_lawyer')->insertGetId([
                        'name'=>$lawyerName,
                        'loid'=>$lawyerOffice
                    ]);
                }else{
                    $lawyer=$lawyer['id'];
                }



                DB::table('C_case_lawyer')->insertGetId([
                    'cid'=>$res,
                    'lid'=>$lawyer
                ]);

            }
        }



        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => $res
            ];
        }else{
            return ThrowApiExc('40003');
        }




    }

    /**
     * 删除案件
     * @param int cid
     * @return array data
     */
    public function delete_case($cid){
        $res = DB::table("c_case")->where("id",$cid)->update(['type'=>0]);
        return [
            'status_code'      => 200,
            'message'     =>  '删除成功',
            'data' => $res
        ];
    }
    /*
     * 查找城市三级联动
     * */

    // public function select_city(Request $request){

    //     $data = DB::select("select c.code as ccode,c.name as cname ,p.name as pname,p.code as pcode from city as c left join province as p on c.provincecode=p.`code` ");
    //     return [
    //         'status_code'      => 200,
    //         'message'     =>  '操作成功',
    //         'data' => $data
    //     ];
    // }

    /**
     * 查询全部省份
     */
    public function select_province(Request $request){
        $res = DB::table("province")->get();
        return [
            'status_code'      => 200,
            'message'     =>  '操作成功',
            'data' => $res
        ];
    }

    /**
     * 查看省份下全部城市
     */
    public function select_city(Request $request){
        $data = $request->only('provincecode');
        $res = DB::table("city")->where('provincecode',$data['provincecode'])->get()->toArray();
        foreach($res as $k=>$v){
            $res[$k]['data']=DB::table("city")->where('provincecode',$v['code'])->get();
        }
        return [
            'status_code'      => 200,
            'message'     =>  '操作成功',
            'data' => $res
        ];
    }

    /**
     * 查询城市下的全部法院
     */
    public function select_city_count(Request $request){
        $data=$request->only('provincecode');
        $res = DB::table("c_court")->where("city",$data['provincecode'])->get();
        return [
            'status_code'      => 200,
            'message'     =>  '操作成功',
            'data' => $res
        ];
    }

    //  /**
    //  * 查询省份下直属法院
    //  */
    // public function select_city_province(Request $request){

    // }

    /*
     * 添加修改案件标签
     * */

     public function update_case_label(Request $request,$cid){

        $data = $request->only("type","lid");

        switch ($data['type']){
            case 1:
                $res =DB::table("C_label_case")->insertGetId([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ]);
            break;
            case 2:
                $res = DB::table("C_label_case")->where([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ])->update([
                    "lid"=>$data['lid']
                ]);
            break;
            case 3:
                $res = DB::table("C_label_case")->where([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ])->delete();
            break;
        }

         if($res){
             return [
                 'status_code'      => 200,
                 'message'     =>  '操作成功',
                 'data' => $res
             ];
         }else{
             return ThrowApiExc('40003');
         }


     }




    /*
     * 更改案件的基本信息11
     * */

    public function update_case_data(Request $request,$cid){

        //律所案号,判决书类型,标题，案由，法院，代出法庭，审判程序,审判人员,原告代理律师，标签，案情概述，案情看点,案件缩影，证据摘要，法律依据
        $data=$request->only("bool","content","case_time","master_number","case_status","title","case_action","court","scourt","subject","json_courtPersonnel","json_y","json_label","json_label_weight","description","description_spot","case_epitome","case_evidence","legal_basis","case_number","baipiId");
        $key="";
        foreach ($data as $k=>$v){
           $inkey = in_array($k,["bool","content","case_time","master_number","case_status","title","case_action","court","scourt","subject","json_courtPersonnel","json_y","json_b","json_label","json_label_weight","description","description_spot","case_epitome","case_evidence","legal_basis","case_number","baipiId"]);
            if($inkey) $key=$k;
        }

        $token = getToken($request);
        $uid =Redis::get("code:".$token);//获取操作人id

        switch ($key){
            case "master_number"://律所案号
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'master_number'=>$data['master_number']
                ]);
            break;
            case "case_status"://判决书类型
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'status'=>$data['case_status']
                ]);
            break;
            case "title"://标题
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'title'=>$data['title']
                ]);
            break;
            case "content"://标题
                $res = DB::table("C_case_data")->where("cid",$cid)->update([
                    'content'=>$data['content']
                ]);
                break;
            case "case_action"://案由
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'case_action'=>$data['case_action']
                ]);
            break;
            case "court"://法院
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'court'=>$data['court']
                ]);
            break;
            case "bool"://法院
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'bool'=>$data['bool']
                ]);
            break;
                case "scourt"://代出法庭
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'scourt'=>$data['scourt']
                ]);
            break;
            case "subject"://审判程序
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'subject'=>$data['subject']
                ]);
            break;
            case "case_number"://审判程序
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'case_number'=>$data['case_number']
                ]);
                break;
            case "json_courtPersonnel"://审判人员
                $type=$request->only('type')['type'];
                $status=$request->only('status')['status'];
                $courtId=$request->only('courtId')['courtId'];



                $json_courtPersonnel = DB::table("C_courtPersonnel")
                                        ->select("id")
                                          ->where([
                                            'name'=>$data['json_courtPersonnel'],
                                            'courtId'=> $courtId
                                        ])
                                        ->first();

                if(!$json_courtPersonnel)
                {
                    $json_courtPersonnel = DB::table("C_courtPersonnel")
                        ->insertGetId([
                            'name'=>$data['json_courtPersonnel'],
                            'courtId'=> $courtId
                        ]);
                }



                $data['json_courtPersonnel']=$json_courtPersonnel['id'];
                if($data['json_courtPersonnel']==0){
                    return ThrowApiExc('50051');
                }

                switch ($type){
                    case 1:
                        $res = DB::table("C_case_cp")->where([
                            "cid"=>$cid,
                            "cpid"=>$data['json_courtPersonnel'],
                            'status'=>$status
                        ])->first();
                        if($res){
                            return ThrowApiExc('58812');
                        }


                        $res = DB::table('C_case_cp')->insert([
                            'cid'=>$cid,
                            'cpid'=>intval($data['json_courtPersonnel']),
                            'status'=>intval($status)
                        ]);

                        break;
                    case 2:
                        $oldCpid=$request->only('oldCpid')['oldCpid'];
                        $res = DB::table('C_case_cp')->where([
                            'cid'=>$cid,
                            'cpid'=>$oldCpid,
                            'status'=>$status
                        ])->update([
                            'cid'=>$cid,
                            'cpid'=>$data['json_courtPersonnel'],
                            'status'=>$status
                        ]);
                        break;
                    case 3:

                        $res = DB::table('C_case_cp')->where([
                                'cid'=>$cid,
                                'cpid'=>$data['json_courtPersonnel'],
                                'status'=>$status
                            ])->delete();
                        $res=1;


                        break;
                }

            break;
            case "json_y"://原告代理律师
                $type=$request->only('type')['type'];
                $json_y=$request->only('json_y')['json_y'];
                $lawyerOfficeold=$request->only('lawyerOffice')['lawyerOffice'];

                $lawyerOffice = DB::table("C_lawyerOffice")
                    ->select("id")
                    ->where("name",$lawyerOfficeold)
                    ->first()['id'];

                if(!$lawyerOffice)
                {
                    $lawyerOffice = DB::table("C_lawyerOffice")
                        ->insertGetId([
                            'name'=>$lawyerOfficeold,
                        ]);
                }

                $json_y = DB::table("C_lawyer")
                    ->select("id")
                    ->where([
                        'name'=>$data['json_y'],
                        'loid'=> $lawyerOffice
                    ])
                    ->first()['id'];
                if(!$json_y)
                {
                    $json_y = DB::table("C_lawyer")
                        ->insertGetId([
                            'name'=>$data['json_y'],
                            'loid'=> $lawyerOffice
                        ]);
                }

                $data['json_y']=$json_y;


                switch ($type){
                    case 1:
                        $res = DB::table('C_case_lawyer')->insertGetId([
                            'cid'=>$cid,
                            'lid'=>$data['json_y']
                        ]);
                        break;
                    case 2:
                        $oldLawyer=$request->only('oldLawyer')['oldLawyer'];
                        $res = DB::table('C_case_lawyer')->where([
                            'cid'=>$cid,
                            'lid'=>$oldLawyer
                        ])->update([
                            'cid'=>$cid,
                            'lid'=>$data['json_y']
                        ]);
                        break;
                    case 3:
                        $res = DB::table('C_case_lawyer')->where([
                            'cid'=>$cid,
                            'lid'=>$data['json_y']
                        ])->delete();
                        break;
                    default:
                        return ThrowApiExc('40003');
                        break;
                }
                $res=1;
            break;
            case "json_label"://标签
                $type=$request->only('type')['type'];

                switch ($type){
                    case 1:
                        $res = DB::table('C_label_case')->insertGetId([
                            'cid'=>$cid,
                            'lid'=>$data['json_label'],
                            'weight'=>$data['json_label_weight']
                        ]);
                        break;
                    case 2:
                        $tid = $request->input('type');
                        $res = DB::table('C_label')->insertGetId(  //新增标签 未审核 返回标签id
                            [
                                'title'=>$data['json_label'],
                                'tid'=>$tid,
                                'uid'=>$uid,
                                'weight'=>$data['json_label_weight']
                            ]
                        );

                        $json_label = DB::table('C_label_case')->insert([ //将新增的标签与案件关联
                            'cid'=>$cid,
                            'lid'=>$res,
                            'uid'=>$uid,
                            'status'=>0
                        ]);
                        break;
                    case 3:
                        $res = DB::table('C_label_case')->where([
                            'cid'=>$cid,
                            'lid'=>$data['json_label']
                        ])->delete();
                        break;
                    default:
                        return ThrowApiExc('40003');
                        break;
                }
            break;
            case "description"://案情概述
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'description'=>$data['description']
                ]);
            break;
            case "description_spot"://案情看点
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'description_spot'=>$data['description_spot']
                ]);
            break;
            case "case_epitome"://案件缩影
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'case_epitome'=>json_encode($data['case_epitome'])
                ]);
            break;
            case "case_time"://审理时间
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'case_time'=>$data['case_time']
                ]);
                break;
            case "legal_basis"://法律依据
                $type=$request->only('type')['type'];
                $number=$request->only('number')['number'];

                switch ($type){
                    case 1:

                        $res = DB::table('C_case_law')->insertGetId([
                            'cid'=>$cid,
                            'lawId'=>$data['legal_basis'],  
                            'number'=>$number
                        ]);
                        $res =1;
                        break;

                    case 2:
                        $oldNumber=$request->only('oldNumber')['oldNumber'];
                        $res = DB::table('C_case_law')->where([
                            'cid'=>$cid,
                            'lawId'=>$data['legal_basis'],
                            'oldNumber'=>$oldNumber
                        ])->update([
                            'cid'=>$cid,
                            'lawId'=>$data['legal_basis'],
                            'number'=>$number
                        ]);
                        break;
                    case 3:

                        $res = DB::table('C_case_law')->where([
                            'cid'=>$cid,
                            'lawId'=>$data['legal_basis'],
                            'number'=>$number
                        ])->delete();
                        break;
                    default:
                        return ThrowApiExc('40003');
                        break;
                }

            break;
            case "case_evidence"://证据摘要
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'case_evidence'=>json_encode($data['case_evidence'])
                ]);
            break;
            case "baipiId":
                $res = DB::table("C_case")->where("id",$cid)->update([
                    'baipiId'=>$data['baipiId']
                ]);
            break;
            default:
            break;
        }

        // if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => 1
            ];
        // }else{
        //     return ThrowApiExc('40003');
        // }

    }

    /*
     * 案件列表
     * @param Request $request
     *        case_acction      案由
     *        title             标题
     *        case_number       案号
     *        master_number     律所案号
     *        court             法院
     *        courtPersonnel    法院人员
     *        lawyer            律师
     *        lawyerOffice      律所
     *        subject           审理程序
     *        case_type         案件类型
     *        time              审理时间
     *        label             标签
     *        law               法律依据
     *
     *
     * */

    public function select_case_list(Request $request){




        $data=$request->only('case_type','case_action','title','content','case_number','court',"courtPersonnel",'subject','case_type','case_time','label',"law","lawyer","lawyerOffice",'status','jieanStatus');

        $where = array();
        $select= ['c1.title',"c1.master_number","c1.case_number_time","c1.create_time",'u.name','c1.id','c1.bool'];

        $OS=new IndexController($request);
        $where[]=['c1.type',1];
        foreach ($data as $k=>$v){

            

            switch ($k){
                case "case_action":
                    $where[]=['c1.case_action','=',$v];
                    $select[]='c1.case_action';
                    break;
                case "case_number":
                    $where[]=['c1.case_number','=',$v];
                    $select[]='c1.case_number';
                     break;
                case "court":
                    $where[]=['c1.court','=',$v];
                    $select[]='c1.court';
                    break;
               case "status":
                   $where[]=['c1.status','=',$v];
                   break;
                case "subject":
                    $where[]=['c1.subject','=',$v];
                    $select[]='c1.subject';
                    break;
                case "courtPersonnel":
                    $where[]=['cp.cpid','=',$v];
                    $select[]='cp.cpid';
                    break;
                case "master_number":
                    $where[]=['c1.master_number','=',$v];
                    break;
                case "label":
                    $where[]=['lc.lid','=',json_decode($v)];
                    $select[]='lc.lid';
                    break;
                case "lawyer":
                    $where[]=['ccl.lid','=',$v];
                    $select[]='ccl.lid';
                    break;
                case "lawyerOffice":
                    $where[]=['clawyer.id','=',$v];
                    $select[]='clawyer.id';
                    break;
                case "case_time":
                    $where[]=['c1.case_time','=',$v];
                    $select[]='c1.case_time';
                    break;
                case "case_type":
                    $where[]=['c1.tid','=',$v];
                    $select[]='c1.tid';
                    break;
                case "law":
                    $where[]=['claw.lawid','=',json_decode($v)[0]];
                    $where[]=['claw.number','=',json_decode($v)[1]];
                    $select[]='claw.lawid';
                    $select[]='claw.number';
                    break;
                case "title":
                    $where[]=['c1.title','=',111111];
                break;
                case "content":
                    $where[]=['c1.title','=',111111];
                    break;
                default:
                break;
            }
        }



        $resData = DB::table('C_case as c1')
            ->select($select)
            ->leftJoin('users as u',"c1.uid","=","u.id")
            ->leftJoin("C_case_cp as cp","cp.cid","=","c1.id")
            ->leftJoin("C_label_case as lc","lc.cid","=","c1.id")
            ->leftJoin("C_case_lawyer as ccl","ccl.cid","=","c1.id")
            ->leftJoin("C_lawyer as clawyer","clawyer.id","=","ccl.lid")
            ->leftJoin("C_case_law as claw","claw.cid","=","c1.id")
            ->distinct();
            

            if(array_key_exists("jieanStatus",$data)&&$data['jieanStatus']==2){
                $jieanBaogaoIds= DB::table('C_case')
                    ->where("type",5)
                    ->select("projectId")
                    ->get()->toArray();
                $jieanBaogaoIds = array_column($jieanBaogaoIds,"projectId");
                $where[]=['c1.type',"!=",5];
                $resData=$resData->whereIn("c1.projectId",$jieanBaogaoIds)
                ->where($where)
                ->orderBy("id","asc")
                ->paginate(20,["c1.id"])->toarray();
            }else{
                $resData=$resData
                ->where($where)
                ->orderBy("id","asc")
                ->paginate(20,["c1.id"])->toarray();
            }
            

            $res = $resData['data'];

        return $resData;
    }

    public function select_case_list_ai(Request $request){  
        $data=$request->only("status",'victory');
        $resData=[];
        $res=DB::table("ai_case_data as acd")
        ->leftJoin("c_case as cc",'cc.id','=','acd.cid')
        ->where([
            ['acd.status',$data['status']],
            ['acd.victory',$data['victory']]
        ])
        ->select("cc.title",'cc.id','acd.status','acd.victory')
        ->paginate(20)
        ->toArray();

        return $res;

    }
    /*
     * 查询案件
     * */

    public function select_case(Request $request,$cid){
        $res = DB::table('c_case as c')
            ->select('c.*','cd.*','co.name as court','co.name as scourt','c.court as courtId','ca.name as case_action','ca.id as case_actionId')
            ->where("c.id",$cid)
            ->leftJoin('c_case_data as cd', 'c.id', '=', 'cd.cid')
            ->leftJoin('C_court as co','c.court','=','co.id')
            ->leftJoin('c_case_action as ca','c.case_action','=','ca.id')
            ->first();
        $label = DB::table('C_label_case as clc')
                ->select('clc.lid','cl.title')
                ->leftJoin('C_label as cl',"cl.id",'=','clc.lid')
                ->where("clc.cid",$cid)
                ->get();
        $lawyer=DB::table('c_case_lawyer as ccl')
            ->select('cl.name as lawyerName','clo.name as lawyerOfficeName',"cl.id")
            ->leftJoin('C_lawyer as cl','cl.id','=','ccl.lid')
            ->leftJoin('C_lawyerOffice as clo','cl.loid','=','clo.id')
            ->where('ccl.cid',$cid)
            ->get();
        $plaintiff=DB::table('C_plaintiff')
                ->where('cid',$cid)
                ->get()->toArray();
        $courtPersonnel=DB::table("c_case_cp as ccp")
                        ->select("ccp.*","cp.name",'cp.courtId')
                        ->leftJoin("C_courtPersonnel as cp","cp.id","=","ccp.cpid")
                        ->where("ccp.cid",$cid)
                        ->get();
        $res['legal_basis']= DB::table("c_case_law")
                        ->where("cid",$cid)
                        ->get();
        $res['label_case']=json_encode($label);
        $res['lawyer']=json_encode($lawyer);
        $res['plaintiff']=json_encode($plaintiff);

        $res['lastId']=DB::table("c_case")->where("id",">",$cid)->orderBy("id","ASC")->first();
        $res['topId']=DB::table("c_case")->where("id","<",$cid)->orderBy("id","DESC")->first();

        // foreach($res['plaintiff'] as $k=>$v){
            
        // }

        $jieanbaogao=DB::table("c_case as c1")
        ->leftJoin("c_case_data as c1d","c1d.cid","=","c1.id")
        ->where([
            ['c1.type',5],
            ['c1.projectId',$res['projectId']]
        ])->orderBy("c1.id","desc")->select("c1.id","c1.title","c1.projectId","c1d.*")->first();

        if($jieanbaogao){
            $res['jieanbaogaoStatus']=1;
            $res['jieanData']=$jieanbaogao;
        }else{
            $res['jieanbaogaoStatus']=0;
        }

        $res['courtPersonnel']=json_encode($courtPersonnel);
        
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        $role_data2=[34];
        // $role_data=[34];
        $role_data=[16,11,12];
        $u1=DB::connection('mysql2')->table('role_user')->where('user_id',$uid)->whereIn('role_id',$role_data)->first();
        $u2=DB::table('role_user')->where('user_id',$uid)->whereIn('role_id',$role_data)->first();
        $imgRole=DB::connection('mysql2')->table('role_user')->where('user_id',$uid)->whereIn('role_id',$role_data2)->first();

        if($uid!=152&&$uid!=484&&$uid!=342&&$uid!=462&&$uid!=491&&$uid!=490&&$uid!=495&&$uid!=23&&$uid!=148&&$uid!=499){
            if($imgRole){
                $res['imgs']="[]";
            }
            if(!$u1&&!$u2){ 
                $str=$res['content'];
                $res['plaintiff']=json_encode(name_head_sort($plaintiff));
                $str=preg_name($str);
                
                
                //屏蔽手机号 身份证号 银行卡号 车牌号 出生日期
                $str=preg_number($str);
                // var_dump($str);die;
    
                $str=preg_address($str);
                $res['content']=$str;
    
            }   
        }

        $aiInfo=DB::table("ai_case_data")->where("cid",$res['cid'])->first();
        $res['aiInfo']=$aiInfo;

        return $res;
        
    }



    public function update_ai_caseStatus(Request $request){
        // $status=$request->status;
        $cid=$request->cid;
        $data=$request->all();
        // $errInfo=$request->errInfo;
        // $victory_info=$request->victory_info;
        // $update=['status'=>$status];

        // if($errInfo){
        //     $update['errInfo']=$errInfo;
        // }
        // if($victory_info){
        //     $update['victory_info']=$victory_info;
        // }
        
        
        

        $res=DB::table("ai_case_data")->where("cid",$cid)->update($data);
        return [
            'code'      => 200,
            'message'     => '修改成功',
            'data'  =>$res
        ];
    }



    /*
     *  更改案件法院人员以及所属法院Id
     * */

    public function update_case_court(Request $request,$cid){

        $data = $request->only('lid','type');

        switch ($data['type']){
            case 1:
                $res =DB::table("C_label_lawer")->insertGetId([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ]);
                break;
            case 2:
                $res = DB::table("C_label_lawer")->where([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ])->update([
                    "lid"=>$data['lid']
                ]);
                break;
            case 3:
                $res = DB::table("C_label_lawer")->where([
                    "lid"=>$data['lid'],
                    "cid"=>$cid
                ])->delete();
                break;
        }

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => $res
            ];
        }else{
            return ThrowApiExc('40003');
        }


    }




    public function pro_aray(){

    }

    public function update_case_create(){


        return create(['court_status','case_status','subject','courtPersonnel']);

    }

    public function all_file(Request $request){
        $data = [];
        $path="./365";
        $files = opendir($path);
     

        while ($rows = readdir($files)){
            if($rows=="."||$rows==".."||$rows==".DS_Store"){
            }else{
                $path2 = $path."/".$rows;
                $files2 = opendir($path2);
                while ($rows2 = readdir($files2)){
                    if($rows2=="."||$rows2==".."||$rows2==".DS_Store"){
                    }else{
                        if(preg_match('/g$/',$rows2)){

                            $data[$rows][]=$path2."/".$rows2;
                            
                        }
                   
                    }
                }
            }
        }

        
        

        $numOne=1;
        foreach ($data as $k=>$v){

                    $res = DB::table("C_case")->where([
                        ["title",$k]
                    ])->first();
                    
                    $numOne++;
                    if($res==null){

                        $this->all2($v,$k,$request);

                    }
                    
          

        }



    }


    public function all2($data,$title,$request,$master_number=0){


        if($master_number===0){
            $master_number=$title;
        }
        // dd($title);

        $res = DB::table('c_case')
            ->where([
                ['title',$title],
                ['bool',1],  
                ['master_number',$master_number],
                // ['id',"<","3332"]
            ])
            ->first();
        if($res){
            // var_dump($res);
            return;
        }
        // echo $title."</br>";
        // return;

    
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        $imgurl=[];
        $imgsNew=[];


        $content="";
        $courtid=0;//法院id
        $case_number=0;//案号
        $case_number_time=0;//案号时间
        $json_content=array();
        $json_contents=array();
        $case_title="";
        $status=0;
        $json=array();
        $num =0;
        $y=[];
        $b=[];
        $lv=[];

        foreach ($data as $k=>$v){
            if(strpos($v,"._")!==false){
                // var_dump($v);
            }else{
                $jpg = explode(".",$v);
                $jpgNums=explode("/",$jpg[1]);
                $imgsNew[$jpgNums[3]]=$v;
            }
            
        }
      


        ksort($imgsNew);
       
        $imgsNew=array_values($imgsNew);
   
        
        // dd($imgsNew);

        foreach ($imgsNew as $k=>$v){

            $jpg = explode(".",$v);
        $imgName=date("YmdHis",time()).rand(1000,9999).rand(1000,9999).".".$jpg[2];

            $imgurl[$k] = Oss($v,$imgName)['info']['url'];
            
            try{
                $json[$k]=json_decode(returnImgJson2($imgurl[$k]),1);
                
            }catch (Exception $e){
                return [
                    'status_code'      => 200,
                    'message'     =>  '操作成功',
                    'data' => $title."失败"
                ];
            }
          
            if(count($imgsNew)-1==$k){

                foreach ($json[$k]['prism_wordsInfo'] as $kk=>$vv){
                    if($vv['word']=="审"||$vv['word']=="代理审"){
                        foreach ($json[$k]['prism_wordsInfo'] as $kkk=>$vvv){
                            if($kkk>=$kk){
                                unset($json[$k]['prism_wordsInfo'][$kkk]);
                            }
                        }
                        break;
                    }
                }

            }
            $json_content=$json[$k]['prism_wordsInfo'];
            $json_contents[]=$json_content;
            $key=0;
            $bigX=500;
            foreach ($json_content as $kk=>$vv){
                if($vv['pos'][0]['x'] < $bigX) $bigX=$vv['pos'][0]['x'];
            }

            if($num==0){

                foreach ($json_content as $kk=>$vv){

                    switch ($kk){
                        case 0:
                            $courtDB=DB::table('C_court')->where('name','like',"%".$vv['word']."%")->first();
                            if($courtDB) $courtid=$courtDB['id'];
                            break;
                        case 1:
                            $status=4;
                            $case_status=substr($vv['word'],-9,9);
                            if(array_key_exists($case_status,create(['case_status'])['case_status'])) $status=create(['case_status'])['case_status'][$case_status];
                            break;
                        case 2:
                            $case_number=$vv['word'];
                            $case_number_time=substr($vv['word'],1,4);
                            break;
                        default:
                            if($vv['pos'][0]['y']-$json_content[$kk-1]['pos'][0]['y']<=3){
                                $content.=$vv['word'];
                            }else {
                                if ($vv['pos'][0]['x'] - $bigX < 50) {
                                    $content .= $vv['word'];
                                } else {
                                    $content = $content . "\n" . $vv['word'];
                                }
                            }
                            break;
                    }
                }
            }else{
                foreach ($json_content as $kk=>$vv){


                    if($vv['pos'][0]['x']-$bigX < 50){
                        $content.=$vv['word'];
                    }else{
                        $content=$content."\n".$vv['word'];
                    }

                }
            }


            $num++;

        }


        $datas = explode("\n" ,$content);
        foreach ($datas as $kk=>$vv){
            if(preg_match('/^(原告：)/u',$vv)){
                $y[]=explode("，",$vv);
                $w=1;
            }   
            if(preg_match('/^(被告：)/u',$vv)){
                $b[]=explode("，",$vv);
                $w=2;
            }
            if(preg_match('/^(委托诉讼代理人：)(.*)(律师。)$/u',$vv)){
                $lv[]=explode("，",$vv);
            }
        }






        $res = DB::table('C_case')->insertGetId(
            [
                'title'=>$title,
                'court'=>$courtid,
                'case_number'=>$case_number,
                'master_number'=>$master_number,
                'create_time'=>date("Y-m-d H:i:s",time()),
                'uid'=>$uid,
                'status'=>$status
            ]
        );

        $res2 = DB::table('C_case_data')->insertGetId(
            [
                'content'=>$content,
                'json_content'=>json_encode($json_contents),
                'imgs'=>json_encode($imgurl),
                'cid'=>$res
            ]
        );


        if(count($y)>0){
            foreach ($y as $k=>$v){
                $name = str_replace("原告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                // var_dump($v);

                $age = str_replace("出生","",$v[2]);
                $age = str_replace(" ","",$age);
                $age =date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>1,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($b)>0){
            foreach ($b as $k=>$v){
                $name = str_replace("被告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                $age = str_replace("出生","",$v[2]);
                $age = str_replace(" ","",$age);
                $age = date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>2,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($lv)>0){
            foreach ($lv as $k=>$v){

                $lawyerName=str_replace("委托诉讼代理人：","",$v[0]);
                $lawyerName = str_replace(" ","",$lawyerName);
                $lawyerOfficeName=str_replace("律师","",$v[1]);
                $lawyerOfficeName = str_replace(" ","",$lawyerOfficeName);
                $lawyerOfficeName = str_replace("。","",$lawyerOfficeName);

                $lawyerOffice=DB::table('C_lawyerOffice')->where('name','like','%'.$lawyerOfficeName.'%')->first();



                if(!$lawyerOffice){
                    $lawyerOffice=DB::table('C_lawyerOffice')->insertGetId([
                        'name'=>$lawyerOfficeName,
                        'status'=>1
                    ]);
                }else{
                    $lawyerOffice=$lawyerOffice['id'];
                }


                $lawyer=DB::table('C_lawyer')->where(
                    [
                        ['name','like','%'.$lawyerName.'%'],
                        ['loid','=',$lawyerOffice]
                    ]
                )->first();



                if(!$lawyer){
                    $lawyer=DB::table('C_lawyer')->insertGetId([
                        'name'=>$lawyerName,
                        'loid'=>$lawyerOffice
                    ]);
                }else{
                    $lawyer=$lawyer['id'];
                }



                DB::table('C_case_lawyer')->insertGetId([
                    'cid'=>$res,
                    'lid'=>$lawyer
                ]);

            }
        }



        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => $res
            ];
        }else{
            return ThrowApiExc('40003');
        }



    }

    

    public function all3(Request $request){
        $master_number=0;
        $title=$request->title;
        $data=$request->data;
        $imgurl=json_decode($data,true);
        $type=$request->type;
        $cid=$request->cid;
        // public function all3($data,$title,$request,$master_number=0){
 
        if($master_number===0){
            $master_number=$title;
        }
        // dd($imgurl);

        $res = DB::table('C_case')
            ->where([
                'title'=>$title,
                'master_number'=>$master_number,
                'type'=>$type
            ])
            ->first();
        // if($res){
        //     return;
        // }
      
    
        $token = getToken($request);

        $uid =$request->uid;

        $user=DB::connection("mysql2")->table("users")->where("id",$uid)->first();

        $userN=DB::table("users")->where("name",$user['name'])->first();

        if($userN){
            $uid=$userN['id'];
        }else{
            $uid=DB::table("users")->insertGetId([
                'name'=>$user['name'],
                'phone'=>$user['phone'],
                'email'=>$user['email'],
                'password'=>$user['password'],
            ]);
        }

        $content="";
        $courtid=0;//法院id
        $case_number=0;//案号
        $case_number_time=0;//案号时间
        $json_content=array();
        $json_contents=array();         
        $case_title="";
        $status=0;
        $json=array();
        $num =0;
        $y=[];
        $b=[];  
        $lv=[];

        $json=[];

        foreach ($imgurl as $k=>$v){

            

            try{

                $json[$k]=json_decode(returnImgJson2($imgurl[$k]['url']),1);
                // dd($json);

                if($json[$k]['content']==""){
                    continue;
                }
                // var_dump($json,$imgurl[$k]['url']);
                
                
            }catch (Exception $e){
                return [
                    'status_code'      => 200,
                    'message'     =>  '操作成功',
                    'data' => $title."失败" 
                ];
            }   
          
            if(count($imgurl)-1==$k){

                foreach ($json[$k]['prism_wordsInfo'] as $kk=>$vv){
                    if($vv['word']=="审"||$vv['word']=="代理审"){
                        foreach ($json[$k]['prism_wordsInfo'] as $kkk=>$vvv){
                            if($kkk>=$kk){
                                unset($json[$k]['prism_wordsInfo'][$kkk]);
                            }
                        }
                        break;
                    }
                }

            }
            $json_content=$json[$k]['prism_wordsInfo'];
            $json_contents[]=$json_content;
            
            $key=0;
            $bigX=500;
            foreach ($json_content as $kk=>$vv){
                if($vv['pos'][0]['x'] < $bigX) $bigX=$vv['pos'][0]['x'];
            }
            

            if($num==0){

                foreach ($json_content as $kk=>$vv){

                    switch ($kk){
                        case 0:
                            $courtDB=DB::table('C_court')->where('name','like',"%".$vv['word']."%")->first();
                            if($courtDB) $courtid=$courtDB['id'];
                            break;
                        case 1:
                            $status=4;
                            $case_status=substr($vv['word'],-9,9);
                            if(array_key_exists($case_status,create(['case_status'])['case_status'])) $status=create(['case_status'])['case_status'][$case_status];
                            break;
                        case 2:
                            $case_number=$vv['word'];
                            $case_number_time=substr($vv['word'],1,4);
                            break;
                        default:
                            if($vv['pos'][0]['y']-$json_content[$kk-1]['pos'][0]['y']<=3){
                                $content.=$vv['word'];
                            }else {
                                if ($vv['pos'][0]['x'] - $bigX < 50) {
                                    $content .= $vv['word'];
                                } else {
                                    $content = $content . "\n" . $vv['word'];
                                }
                            }
                            break;
                    }
                }
            }else{
                foreach ($json_content as $kk=>$vv){
                    if($vv['pos'][0]['x']-$bigX < 50){
                        $content.=$vv['word'];
                    }else{
                        $content=$content."\n".$vv['word'];
                    }

                }
            }


            $num++;

        }
        $datas = explode("\n" ,$content);
        foreach ($datas as $kk=>$vv){
            if(preg_match('/^(原告：)/u',$vv)){
                $y[]=explode("，",$vv);
                $w=1;
            }   
            if(preg_match('/^(被告：)/u',$vv)){
                if(strlen($vv)<50){
                    $vv=$vv.$datas[$kk+1];
                }
                $b[]=explode("，",$vv);
                $w=2;
            }
            if(preg_match('/^(委托诉讼代理人：)(.*)(律师。)$/u',$vv)){
                $lv[]=explode("，",$vv);
            }
        }


        if($cid==0){
            $res = DB::table('C_case')->insertGetId(
                [
                    'title'=>$title,
                    'projectId'=>$request->projectId,
                    'aladinId'=>$request->aladinId,
                    'court'=>$courtid,
                    'case_number'=>$case_number,
                    'master_number'=>$master_number,
                    'create_time'=>date("Y-m-d H:i:s",time()),
                    'uid'=>$uid,
                    'type'=>$type,
                    'status'=>$status
                ]
            );
    
            $res2 = DB::table('C_case_data')->insertGetId(
                [
                    'content'=>$content,
                    'json_content'=>json_encode($json_contents),
                    'imgs'=>json_encode(array_column($imgurl,"url")),
                    'cid'=>$res
                ]
            );
        }else{
            $res = $cid;
            var_dump($content);
            $res2 = DB::table('C_case_data')->where("cid",$cid)->update(
                [
                    'content'=>$content,
                    'json_content'=>json_encode($json_contents),
                    'imgs'=>json_encode(array_column($imgurl,"url")),
                    'cid'=>$res
                ]
            );
            
        }



        


        if(count($y)>0){
            foreach ($y as $k=>$v){
                $name = str_replace("原告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                // var_dump($v);

                

                if(strstr($v[2],"出生")){
                    $age = str_replace("出生","",$v[2]);
                }else{
                    $age = "未识别";
                }

                $age = str_replace(" ","",$age);
                $age =date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>1,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($b)>0){
            foreach ($b as $k=>$v){
                $name = str_replace("被告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                if(strstr($v[2],"出生")){
                    $age = str_replace("出生","",$v[2]);
                }else{
                    $age = "未识别";
                }
                $age = str_replace(" ","",$age);
                $age = date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>2,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($lv)>0){
            foreach ($lv as $k=>$v){

                $lawyerName=str_replace("委托诉讼代理人：","",$v[0]);
                $lawyerName = str_replace(" ","",$lawyerName);
                $lawyerOfficeName=str_replace("律师","",$v[1]);
                $lawyerOfficeName = str_replace(" ","",$lawyerOfficeName);
                $lawyerOfficeName = str_replace("。","",$lawyerOfficeName);

                $lawyerOffice=DB::table('C_lawyerOffice')->where('name','like','%'.$lawyerOfficeName.'%')->first();



                if(!$lawyerOffice){
                    $lawyerOffice=DB::table('C_lawyerOffice')->insertGetId([
                        'name'=>$lawyerOfficeName,
                        'status'=>1
                    ]);
                }else{
                    $lawyerOffice=$lawyerOffice['id'];
                }


                $lawyer=DB::table('C_lawyer')->where(
                    [
                        ['name','like','%'.$lawyerName.'%'],
                        ['loid','=',$lawyerOffice]
                    ]
                )->first();
                        


                if(!$lawyer){
                    $lawyer=DB::table('C_lawyer')->insertGetId([
                        'name'=>$lawyerName,
                        'loid'=>$lawyerOffice
                    ]);
                }else{
                    $lawyer=$lawyer['id'];
                }



                DB::table('C_case_lawyer')->insertGetId([
                    'cid'=>$res,
                    'lid'=>$lawyer
                ]);

            }
        }



        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => $res
            ];
        }else{
            return ThrowApiExc('40003');
        }



    }


    public function all4($id){

        $imgs = DB::table("c_case_data")->where("cid",$id)->first();
        $imgurl=json_decode($imgs['imgs'],true);
        // dd($imgurl);
        // $imgurl=json_decode($data,true);
 

        $content="";
        $courtid=0;//法院id
        $case_number=0;//案号
        $case_number_time=0;//案号时间
        $json_content=array();
        $json_contents=array();         
        $case_title="";
        $status=0;
        $json=array();
        $num =0;
        $y=[];
        $b=[];  
        $lv=[];

        $json=[];

        foreach ($imgurl as $k=>$v){

            

            try{

                $json[$k]=json_decode(returnImgJson2($v),1);
                // dd($json);

                if($json[$k]['content']==""){
                    continue;
                }
                // var_dump($json,$imgurl[$k]['url']);
                
                
            }catch (Exception $e){
                return [
                    'status_code'      => 200,
                    'message'     =>  '操作成功',
                    'data' => $title."失败" 
                ];
            }   
          
            if(count($imgurl)-1==$k){

                foreach ($json[$k]['prism_wordsInfo'] as $kk=>$vv){
                    if($vv['word']=="审"||$vv['word']=="代理审"){
                        foreach ($json[$k]['prism_wordsInfo'] as $kkk=>$vvv){
                            if($kkk>=$kk){
                                unset($json[$k]['prism_wordsInfo'][$kkk]);
                            }
                        }
                        break;
                    }
                }

            }
            $json_content=$json[$k]['prism_wordsInfo'];
            $json_contents[]=$json_content;
            
            $key=0;
            $bigX=500;
            foreach ($json_content as $kk=>$vv){
                if($vv['pos'][0]['x'] < $bigX) $bigX=$vv['pos'][0]['x'];
            }
            

            if($num==0){

                foreach ($json_content as $kk=>$vv){

                    switch ($kk){
                        case 0:
                            $courtDB=DB::table('C_court')->where('name','like',"%".$vv['word']."%")->first();
                            if($courtDB) $courtid=$courtDB['id'];
                            break;
                        case 1:
                            $status=4;
                            $case_status=substr($vv['word'],-9,9);
                            if(array_key_exists($case_status,create(['case_status'])['case_status'])) $status=create(['case_status'])['case_status'][$case_status];
                            break;
                        case 2:
                            $case_number=$vv['word'];
                            $case_number_time=substr($vv['word'],1,4);
                            break;
                        default:
                            if($vv['pos'][0]['y']-$json_content[$kk-1]['pos'][0]['y']<=3){
                                $content.=$vv['word'];
                            }else {
                                if ($vv['pos'][0]['x'] - $bigX < 50) {
                                    $content .= $vv['word'];
                                } else {
                                    $content = $content . "\n" . $vv['word'];
                                }
                            }
                            break;
                    }
                }
            }else{
                foreach ($json_content as $kk=>$vv){
                    if($vv['pos'][0]['x']-$bigX < 50){
                        $content.=$vv['word'];
                    }else{
                        $content=$content."\n".$vv['word'];
                    }

                }
            }


            $num++;

        }

        $datas = explode("\n" ,$content);

        foreach ($datas as $kk=>$vv){
            if(preg_match('/^(原告：)/u',$vv)){
                $y[]=explode("，",$vv);
                $w=1;
            }   
            if(preg_match('/^(被告：)/u',$vv)){
                if(strlen($vv)<50){
                    $vv=$vv.$datas[$kk+1];
                }
                $b[]=explode("，",$vv);
                $w=2;
            }
            if(preg_match('/^(委托诉讼代理人：)(.*)(律师。)$/u',$vv)){
                $lv[]=explode("，",$vv);
            }
        }






        $res = DB::table('C_case')->where("id",$id)->update(
            [
                'court'=>$courtid,
                'case_number'=>$case_number,
                'create_time'=>date("Y-m-d H:i:s",time()),
            ]
        );

        $res2 = DB::table('C_case_data')->where("cid",$id)->update(
            [
                'content'=>$content,
                'json_content'=>json_encode($json_contents)
            ]
        );


        if(count($y)>0){
            foreach ($y as $k=>$v){
                $name = str_replace("原告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                // var_dump($v);

                

                if(strstr($v[2],"出生")){
                    $age = str_replace("出生","",$v[2]);
                }else{
                    $age = "未识别";
                }

                $age = str_replace(" ","",$age);
                $age =date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>1,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($b)>0){
            foreach ($b as $k=>$v){
                $name = str_replace("被告：","",$v[0]);
                $name = str_replace(" ","",$name);
                $sex =  str_replace(" ","",$v[1]);
                if($sex == "男"){
                    $sex = 1;
                }else{
                    $sex = 0;
                }
                if(strstr($v[2],"出生")){
                    $age = str_replace("出生","",$v[2]);
                }else{
                    $age = "未识别";
                }
                $age = str_replace(" ","",$age);
                $age = date_parse_from_format('Y年m月d日',$age);
                $age = mktime(0,0,0,$age['month'],$age['day'],$age['year']);

                DB::table("C_plaintiff")->insertGetId([
                    'status'=>2,
                    'name'=>$name,
                    'age'=>date("Y-m-d H:i:s",$age),
                    'cid'=>$res,
                    'sex'=>$sex
                ]);
            }
        }

        if(count($lv)>0){
            foreach ($lv as $k=>$v){

                $lawyerName=str_replace("委托诉讼代理人：","",$v[0]);
                $lawyerName = str_replace(" ","",$lawyerName);
                $lawyerOfficeName=str_replace("律师","",$v[1]);
                $lawyerOfficeName = str_replace(" ","",$lawyerOfficeName);
                $lawyerOfficeName = str_replace("。","",$lawyerOfficeName);

                $lawyerOffice=DB::table('C_lawyerOffice')->where('name','like','%'.$lawyerOfficeName.'%')->first();



                if(!$lawyerOffice){
                    $lawyerOffice=DB::table('C_lawyerOffice')->insertGetId([
                        'name'=>$lawyerOfficeName,
                        'status'=>1
                    ]);
                }else{
                    $lawyerOffice=$lawyerOffice['id'];
                }


                $lawyer=DB::table('C_lawyer')->where(
                    [
                        ['name','like','%'.$lawyerName.'%'],
                        ['loid','=',$lawyerOffice]
                    ]
                )->first();
                        


                if(!$lawyer){
                    $lawyer=DB::table('C_lawyer')->insertGetId([
                        'name'=>$lawyerName,
                        'loid'=>$lawyerOffice
                    ]);
                }else{
                    $lawyer=$lawyer['id'];
                }



                DB::table('C_case_lawyer')->insertGetId([
                    'cid'=>$res,
                    'lid'=>$lawyer
                ]);

            }
        }



        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '操作成功',
                'data' => $res
            ];
        }else{
            return ThrowApiExc('40003');
        }



    }

    public function all4_ret(){
        $datas = DB::table("c_case as cc")
        ->leftJoin("c_case_data as ccd",'ccd.cid',"=",'cc.id')
        ->whereNotNull("cc.aladinId")
        ->whereNotNull("ccd.imgs")
        ->where("ccd.content","")
          ->where("cc.status","!=","4")
        // ->count();
        ->limit(20)
        ->get()->toArray();
        // dd($datas);
        foreach($datas as $k=>$v){
            $res=$this->all4($v['id']);
            // dd($v['id']);
        }

    }

    public function all4remake(){
        $datas = DB::table("c_case")->where("id",">","3910")->get()->toArray();
        foreach($datas as $k=>$v){
            DB::table("c_case")->where("id",$v['id'])->update([
                'linkCreatedtime'=>1,
                'case_time'=>$v['create_time']
            ]);
        }
    }


    public function demo222333(){

        $data = DB::table("C_case_data")
                ->select("content","cid")
                ->where("cid",">","190")
                ->get();



        foreach ($data as $k=>$v) {

            $re = '/依[据照].*条/';
            preg_match($re, $v['content'], $falv);



                if (strpos($falv[0], '及') !== false) {

                    $falv = explode("及", $falv[0]);
                } else if (strpos($falv[0], '，') !== false) {
                    $falv = explode("，", $falv[0]);
                }

//            $pattern="/[及]/";
//            $spr=preg_split($pattern,"111及1111及123123");


                foreach ($falv as $kkk => $vvv) {
                    $reLv = "/第.*条/";
                    preg_match($reLv, $vvv, $res3);
                    $tiao = explode("、", $res3[0]);


                    $reFa = "/《.*》/";
                    preg_match($reFa, $vvv, $fa);

                    $faData = DB::table("C_law")
                        ->where("name", $fa[0])
                        ->first();

                    $reNumber = '/[\x{1F600}-\x{1F64F}]/u';

                    foreach ($tiao as $kk => $vv) {

                        $num = checkNatInt($vv);

                        DB::table("C_case_law")
                            ->insert([
                                'cid' => $v['cid'],
                                'lawId' => $faData['id'],
                                'number' => $num
                            ]);

                    }
                }
                


        }

    }

    public function demo222333333(){
        $data = DB::table("C_case_data")
            ->select("content","cid","case_number")
            ->leftJoin("C_case","C_case.id","=","C_case_data.cid")
            ->where("cid",">","99")
            ->get();
        foreach ($data as $k=>$v){
            $re = '/\([0-9]{4}\).*[0-9]{4}.*[0-9]{4,5}号/';
            preg_match($re, $v['content'], $res3);
            if(count($res3)>0){
                if(strlen($v['case_number'])<20||strlen($v['case_number'])>30){
                    if(strlen($res3[0])>24&&strlen($res3[0])<30){
                        var_dump($v['cid']);
                        var_dump(strlen($res3[0]));
                        var_dump($v['case_number']);
                        var_dump($res3[0]);
                        DB::table("C_case")
                            ->where("id",$v['cid'])
                            ->update([
                                'case_number'=>$res3[0]
                            ]);
                    }
                }

            }

        }
    }

    public function demo2223233(){
        $data = DB::table("C_lawyerOffice")
            ->get();
        foreach ($data as $k=>$v){
            $res = explode("律师事务所",$v['name']);
            $res = $res[0]."事务所";
            DB::table("C_lawyerOffice")
                ->where("id",$v['id'])
                ->update([
                    'name'=>$res
                ]);
        }
    }

    public function demo222(){
       echo 123;
    }


}
